#!/usr/bin/env python
# coding=utf-8

import copy
from oslo_log import log as logging


LOG = logging.getLogger(__name__)

DEFAULT_PATH = {
    "NOVA_CONFIG_PATH": "/etc/nova/nova.conf",
}

DEFAULT_SUPPORT_DEVICE = {
{% for host in pass_through_servers %}
{% set item = hostvars[host]['ansible_local']['openstack_ansible']['nova'] %}
"{{ item.name }}": {"vendor_id": "{{ item.vendor_id }}", "product_id": "{{ item.product_id }}", "device_type": "{{ item.device_type }}", "name": "{{ item.name }}", "gpu_filter":"True"}{% if not loop.last %},{% endif %}
{% endfor %}
}

class ConfigPciDevice(object):
    def __init__(self):
        self.pci_dev_list = []

    def conduct_alias_whilelist_data(self, product_name):
        return DEFAULT_SUPPORT_DEVICE.get(product_name,None)

    def _write_alias_whitelist(self,dev_list, _filter=None):

        try:
            with open(DEFAULT_PATH.get("NOVA_CONFIG_PATH"), 'a+') as f:
                f.seek(0)
                item_list = f.readlines()
                old_whitelist = ""
                for item in item_list[:]:
                    if ("[pci]" in item) or ("passthrough_whitelist" in item) or ("alias" in item):
                        if "passthrough_whitelist" in item:
                            old_whitelist = item
                        item_list.remove(item)

                head = '[pci]' + '\n'
                whitelist = 'passthrough_whitelist = ' + str(dev_list).replace("'","\"") + '\n'
                if whitelist == old_whitelist:
                    print "no changed"
                    return True

                item_list.append(head)
                item_list.append(whitelist)
                for dev in dev_list:
                    dev.pop("gpu_filter")
                    alias = 'alias = ' + str(dev).replace("'","\"") + '\n'
                    item_list.append(alias)

                f.seek(0)
                f.truncate()
                f.write(''.join(item_list))
                print "changed"
            return True
        except Exception as e:
            LOG.info('write_alias_whitelist: _write_alias_whitelist failed error info is :: %s', str(e))
            return False

    def write_alias_whitelist_plus(self):
        pci_dev_list = []
        default_pci_dev = copy.deepcopy(DEFAULT_SUPPORT_DEVICE)
        for prodcut_name,pci_data_dict in default_pci_dev.items():
            pci_dev_list.append(pci_data_dict)

        self._write_alias_whitelist(pci_dev_list)


if __name__ == '__main__':
    obj = ConfigPciDevice()
    obj.write_alias_whitelist_plus()

